/*添加角色*/
var addRole = new Vue({
    el: "#addRole",
    data: function () {
        return {
            treeAddVisible: false,
            labelPosition: 'right',
            isEdit: false,
            roleForm: {
                id: "",
                roleName: "",
                description: "",
                isEnable: "1"
            },
            rules: {
                roleName: [{
                    required: true,
                    message: '请输入角色名称',
                    trigger: 'blur'
                }]
            }
        };
    },
    computed: {
        title: function () {
            return this.isEdit ? "编辑角色" : "新增角色"
        },
        isEditAdmin: function () {
            return this.roleForm.id !== "ADMINISTRATORS";
        }
    },
    methods: {
        submitForm: function (formName, e) {
            var self = this;
            this.$refs[formName].validate(function (valid) {
                if (valid) {
                    var url = self.isEdit ? "/sys/role/modifyRoleInfo" : "/sys/role/addRole";
                    VanyAjax(url, self.roleForm).done(function (data) {
                        this.hide();
                        this.resetForm("roleForm");
                        qxgl.getData();
                    }, true, self);
                } else {
                    VanyAjax.prototype.hideLoading();
                    e.stopPropagation();
                    return false;
                }
            });
        },
        show: function () {
            this.treeAddVisible = true;
        },
        hide: function () {
            this.treeAddVisible = false;
        },
        //重置
        resetForm: function (formName) {
            try {
                this.$refs[formName].resetFields();
            } catch (e) {

            }
            this.roleForm.id = "";
            this.roleForm.roleName = "";
            this.roleForm.description = "";
            this.roleForm.isEnable = "1";
        }
    },
    updated: function () {
        Jurisdiction();
    }
});

/*角色人员*/
var rolePerson = new Vue({
    el: "#rolePerson",
    data: function () {
        return {
            //url: "/templates/authority/qxgl/json/rolePerson.json",
            url: "/sys/role/loadRoleUserInfo",
            params: {
                condition: {
                    roleId: "",
                    searchKey: ""
                },
                token: sessionStorage.token,
                current: 1,
                size: 100
            },
            curRoleName: "",
            nodataFlag: false,
            rolePersonVisible: false,
            tableData: [],
            sels: [],
            firstLoad: true
        }
    },
    computed: {
        height: function () {
            if (window.innerHeight <= 768) {
                return 350;
            } else {
                return 500;
            }
        }
    },
    methods: {
        /**
         * 函数节流器
         */
        _throttle: function (method, context) {
            clearTimeout(method.tId);
            var _arguments_ = arguments;
            method.tId = setTimeout(function () {
                var args = [];
                for (var i = 1; i < _arguments_.length; i++) {
                    args.push(_arguments_[i]);
                }
                method.apply(this, args);
            }, 100);
        },
        /**
         * 判断一个可滚动元素是否滚动到了底部
         */
        _isScrollToBottom: function (e, fn) {
            // e.srcElement存在兼容性问题，并非标准特性
            // https://developer.mozilla.org/zh-CN/docs/Web/API/Event/target
            // 支持 IE6-8
            var target_ = e.target || e.srcElement,
                // 距离顶部高度
                scrollTop = target_.scrollTop,
                // 滚动区域高度
                scrollHeight = target_.scrollHeight,
                // 文档元素高度
                clientHeight = target_.clientHeight;
            // 文档坐标和视口坐标转换，判断元素滚动到了底部
            if (scrollTop + clientHeight == scrollHeight) {
                if (fn) {
                    fn.call(this);
                }
            }
        },
        show: function (roleName) {
            this.curRoleName = roleName;
            this.rolePersonVisible = true;
        },
        hide: function () {
            this.rolePersonVisible = false;
        },
        // 人员筛选器
        openPersonFilter: function () {
            var self = this;
            if (!this.personFilter) {
                this.personFilter = VanyFilter({
                    mountEl: "#content",
                    title: "选择人员",
                    tabs: [{
                        "name": "人员",
                        "id": "renyuan",
                        "filterUrl": "/base/userCondition/getCondition",
                        "url": "/base/userCondition/getBaseUserInfo",
                        "pagination": true,
                        "isPersonSeleted": true,
                        "defaultProps": {
                            "children": 'children',
                            "label": 'userName',
                            "id": "userId"
                        }
                    }],
                    ok: function () {
                        VanyAjax("/sys/role/modifyRoleUser", {
                            roleId: self.params.condition.roleId,
                            userIds: this.tabs[0].allNodesId.join(",")
                        }, "POST", ".vanymodal_vueversion").done(function (data) {
                            this.personFilter.hide();
                            this.personFilter.destroy();
                            this.personFilter = null;
                            this.resetPaginationParams();
                            this.getData();
                        }, true, self);
                        return false;
                    }
                });
            } else {
                this.personFilter.show();
            }
        },
        filterTable: function () {
            this.resetPaginationParams();
            this.getData();
        },
        restore: function () {
            if (this.params.condition.searchKey.length === 0) {
                this.resetPaginationParams();
                this.getData();
            }
        },
        selectable: function (row, index) {
            if (row.userAccount === "admin") {
                return false;
            } else {
                return true;
            }
        },
        getData: function () {
            VanyAjax(this.url, this.params, "GET", "#rolePerson .el-table").done(function (data) {
                if (data.total === 0) {
                    this.nodataFlag = true;
                    return;
                }
                if (this.params.current * this.params.size >= data.total) {
                    this.nodataFlag = true;
                }
                this.tableData = this.tableData.concat(data.records);
                this.params.current++;
                if (this.firstLoad) {
                    var self = this;
                    var tablebody_ = this.$refs["table"].$el;
                    tablebody_ = tablebody_.getElementsByClassName("el-table__body-wrapper")[0];
                    tablebody_.onscroll = function (e) {
                        self._throttle(self._isScrollToBottom, e, self.getData);
                    };
                    this.firstLoad = false;
                }
            }, false, this);
        },
        resetPaginationParams: function () {
            this.tableData = [];
            this.params.current = 1;
            this.nodataFlag = false;
            this.sels = [];
        },
        remove: function () {
            if (this.sels.length === 0) {
                this.$alert('请选择要删除的角色。', '提示', {
                    type: 'warning',
                    customClass: "notLoadingThis"
                });
                return false;
            }
            var self = this;
            self.$confirm("是否进行批量删除操作", '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(function () {
                VanyAjax("/sys/role/deleteRoleUser", {
                    roleId: self.params.condition.roleId,
                    userIds: self.sels.map(function (item) {
                        return item.id;
                    }).join(",")
                }).done(function (data) {
                    for (var i = 0; i < this.sels.length; i++) {
                        for (j = 0; j < this.tableData.length; j++) {
                            if (this.sels[i].account_number === this.tableData[j].account_number) {
                                this.tableData.splice(j, 1);
                                break;
                            }
                        }
                    }
                    this.sels = [];
                    this.$refs["table"].clearSelection();
                }, true, self);
            });
        },
        selsChange: function (sels) {
            this.sels = sels;
        },
        handleClose: function () {
            this.resetPaginationParams();
            this.params.condition.searchKey = "";
            try {
                this.personFilter.destroy();
                this.personFilter = null;
            } catch (e) {
            }
        }
    },
    updated: function () {
        Jurisdiction();
    }
});

//功能权限树
var roleFunctionTree = new Vue({
    el: "#roleFunctionTree",
    data: function () {
        return {
            visible: false,
            treeData: [],
            filterText: "",
            defaultProps: {
                children: "children",
                label: "nameCh"
            }
        }
    },
    computed: {
        style: function () {
            if (window.innerHeight <= 768) {
                return {
                    height: "350px",
                    "overflow-y": "auto"
                }
            } else {
                return {
                    height: "500px",
                    "overflow-y": "auto"
                }
            }
        }
    },
    watch: {
        filterText: function (val) {
            this.$refs.tree.filter(val);
        }
    },
    methods: {
        show: function () {
            this.treeData = [];
            this.visible = true;
        },
        hide: function () {
            this.visible = false;
        },
        filterNode: function (value, data) {
            if (!value) {
                return true;
            } else {
                try {
                    return data[this.defaultProps.label].indexOf(value) !== -1;
                } catch (e) {
                    return true;
                }
            }
        },
        initTransfer: function (params) {
            this.roleId = params.condition.roleId;
            VanyAjax("/sys/role/loadFunctionByRoleCode", params, "GET").done(function (data) {
                this.treeData = data.ownMenuList;
                var checkedKeys = data.allotIds;
                this.$refs["tree"].setCheckedKeys(checkedKeys);
            }, false, this);
        },
        save: function () {
            var checkedKeys = this.$refs["tree"].getCheckedKeys().join(",");
            VanyAjax("/sys/role/modifyRoleFunctionAllotAndRemove", {
                roleId: this.roleId,
                menuIds: checkedKeys
            }).done(function (data) {
                this.hide();
            }, true, this);
        }
    },
    updated: function () {
        Jurisdiction();
    }
});

//数据权限树
var roleDataTree = new Vue({
    el: "#roleDataTree",
    data: function () {
        return {
            visible: false,
            treeData: [],
            filterText: "",
            defaultProps: {
                children: "children",
                label: "orgName"
            }
        }
    },
    computed: {
        style: function () {
            if (window.innerHeight <= 768) {
                return {
                    height: "350px",
                    "overflow-y": "auto"
                }
            } else {
                return {
                    height: "500px",
                    "overflow-y": "auto"
                }
            }
        }
    },
    watch: {
        filterText: function (val) {
            this.$refs.tree.filter(val);
        }
    },
    methods: {
        show: function () {
            this.treeData = [];
            this.visible = true;
        },
        hide: function () {
            this.visible = false;
        },
        filterNode: function (value, data) {
            if (!value) {
                return true;
            } else {
                try {
                    return data[this.defaultProps.label].indexOf(value) !== -1;
                } catch (e) {
                    return true;
                }
            }
        },
        initTransfer: function (params) {
            this.roleId = params.roleId;
            VanyAjax("/sys/role/loadDataByRoleCode", params, "GET").done(function (data) {
                this.treeData = data.ownOrgList;
                var checkedKeys = allotCodes;
                this.$refs["tree"].setCheckedKeys(checkedKeys);
            }, false, this);
        },
        save: function () {
            var checkedKeys = this.$refs["tree"].getCheckedKeys().join(",");
            VanyAjax("/sys/role/modifyRoleDataAllotAndRemove", {
                roleId: this.roleId,
                orgCodes: checkedKeys
            }).done(function (data) {
                this.hide();
            }, true, this);
        }
    },
    updated: function () {
        Jurisdiction();
    }
});